<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="退料单号" prop="code">
          <CodeRuleInput
            :band-value.sync="formData.code"
            table-name="production_return"
            column-name="code"
            :is-edit="id"
          />
        </el-form-item>
        <el-form-item label="任务单号" class="clickChoose">
          <el-input v-model="formData.productTaskCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseOrder"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="退料人员">
          <el-input v-model="formData.returnName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="退料日期">
          <el-date-picker
            v-model="formData.returnDate"
            type="date"
            placeholder="选择日期"
            :editable="false"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div class="formItem_header">
        物料明细
        <div class="formItem_header_operate">
          <a class="formItem_header_operate_item" @click="addRow">
            <svg-icon icon-class="新增" />
            <div class="item_name">添加</div>
          </a>
          <a class="formItem_header_operate_item delete" @click="removeRow">
            <svg-icon icon-class="删除" />
            <div class="item_name">删除</div>
          </a>
        </div>
      </div>
      <div
        ref="table_container"
        class="table_container draggableTable"
      >
        <el-table
          ref="table"
          :data="tableData"
          :height="tableHeight"
          stripe
          border
          style="width: 99.9%;"
          :header-cell-class-name="headerCellClassName"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" width="70" align="center" />
          <el-table-column label="物料编码" min-width="120" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格型号" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料分类" min-width="100" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ scope.row.materialTypeName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料单位" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.materialUnitName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="可退数量" :min-width="SETTINGS.settings_decimalDigits_length">
            <template slot-scope="scope">
              <span>{{ scope.row.nowReturnNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column label="退料数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="returnNumber">
            <template slot-scope="scope">
              <el-input v-model="scope.row.returnNumber" placeholder="请输入" clearable />
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入" clearable />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit('0')">保存</el-button>
      <el-button @click.stop="onSubmit('1')">提交</el-button>
    </div>
  </div>
</template>

<script>
import {
  addOrUpdate,
  getInfo
} from '@/api/ProductionManagement/materialReturn'
import { getInfoForReturn } from '@/api/ProductionManagement/pickingList'
import chooseOrder from './chooseOrder'
import addMaterial from './addMaterial.vue'
import moment from 'moment'
import Big from 'big.js'
import {
  newgetInfo
} from '@/api/ProductionManagement/taskSheet'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  data() {
    return {
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      formData: {
        id: '',
        code: '',
        productionTaskId: '',
        productTaskCode: '',
        returnName: '',
        returnBy: '',
        returnDate: '',
        remark: '',
        model: '',
        data: []
      },
      tableData: [],
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      tableHeight: '325',
      mainId: 'id',
      peopleData: {},
      newText: '',
      rules: {
        code: [
          { required: true, message: '领取单号不能为空', trigger: 'blur' }
        ],
        productTaskCode: [
          { required: true, message: '领料单号不能为空', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    if (!this.id) {
      // 没有id就是新增
      Object.keys(this.defaultValue).forEach((key) => {
        // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else {
      // 有id就是编辑
      this.getInfo()
      this.formData.id = this.id
    }
  },
  mounted() {
    this.formData.returnName = this.$store.state.user.name
    this.formData.returnBy = this.$store.state.user.userId
    this.formData.returnDate = moment(new Date()).format('YYYY-MM-DD')
  },
  methods: {
    headerCellClassName(data) {
      if (['returnNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    chooseOrderCallBack(data) { // 生产任务单号回调
      this.formData.productionTaskId = data.id
      this.formData.productTaskCode = data.code
      this.formData.model = data.model
      getInfoForReturn(data.id).then(res => {
        this.tableData = res.data.rawMaterialPoolListVos
        this.tableData.filter(item => {
          item.productionRawMaterialId = item.id
          item.nowReturnNumber = item.number || 0
        })
        this.formData.requisitionOrReturn = res.data.requisitionOrReturn
      })
    },
    chooseMaterialCallBack(data) {
      const cacheTableData = []
      data.filter((item, index) => {
        if (this.tableData.some(item2 => item2.materialId == item.materialId)) {
          cacheTableData.push(this.tableData.filter(item2 => item2.materialId == item.materialId)[0])
        } else {
          item.nowReturnNumber = item.number || 0
          item.productionRawMaterialId = item.id
          cacheTableData.push(item)
        }
        if (index == data.length - 1) {
          this.tableData = cacheTableData
        }
      })
    },
    showMaterial(data) {
      data.forEach(ele => {
        delete ele.remark
      })
      this.tableData = data
    },
    cellClassName(data) {
      if (data.column.property == 'operate') {
        if (data.rowIndex % 2 == 0) {
          // 单数行
          return 'fixed one'
        } else {
          // 双数行
          return 'fixed two'
        }
      }
    },
    rowClassName({ row, rowIndex }) {
      if (rowIndex == this.tableData.length - 1) {
        return 'addRow'
      }
    },
    addRow() {
      if (this.formData.productTaskCode) {
        this.$layer.iframe({
          // 弹框
          content: {
            content: addMaterial, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              selectedRow: this.tableData,
              id: this.formData.productionTaskId ? this.formData.productionTaskId : ''
            } // props
          },
          area: ['1320px', '700px'],
          title: '选择物料', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      } else {
        this.$message.warning('请选择任务单号')
        return
      }
    },
    chooseOrder() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseOrder, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.listData,
            id: this.formData.productionTaskId
          } // props
        },
        area: ['880px', '700px'],
        title: '选择任务单号', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    removeRow(row) {
      this.tableData = this.tableData.filter((ele) => this.selectionsAll.every((item) => ele.id !== item.id))
    },
    getInfo() {
      getInfo(this.id).then((res) => {
        Object.keys(this.formData).forEach((key) => {
          // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.tableData = this.formData.data
        if (res.data.productionTaskId) {
          // 调用任务单的getInfo，拿model
          newgetInfo(res.data.productionTaskId).then(res2 => {
            this.formData.model = res2.data.model
          })
        }
      })
    },
    materialNameArr(arr) {
      var newArr = arr.filter(function(item, index) {
        return arr.indexOf(item) === index // 因为indexOf 只能查找到第一个
      })
      return newArr
    },
    // 提交
    onSubmit(num) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.tableData.length == 0) {
            this.$message.warning('请添加物料明细')
            return
          }
          if (this.tableData && this.tableData.filter(item => !item.returnNumber).length > 0) {
            this.$message.warning('退料数量不能为空')
            return
          }
          if (this.tableData && this.tableData.filter(item => item.returnNumber && !this.SETTINGS.reg_no_zero.test(item.returnNumber)).length > 0) {
            this.$message.warning('退料数量未正确填写')
            return
          }
          if (this.formData.model == '1') { // BOM模式
            let returnNumberNameList = []
            this.tableData.filter(item => {
              if (Number(item.nowReturnNumber) <= Number(item.returnNumber)) {
                if (returnNumberNameList.length < 3) {
                  returnNumberNameList.push(item.materialName)
                } else {
                  returnNumberNameList.push('等物料')
                }
                returnNumberNameList = this.materialNameArr(returnNumberNameList)
              }
            })
            if (returnNumberNameList.includes('等物料')) {
              returnNumberNameList.splice(returnNumberNameList.indexOf('等物料'), 1)
              returnNumberNameList += '等物料'
            }
            console.log('returnNumberNameList', returnNumberNameList)

            if (this.tableData.filter(item => (Number(item.returnNumber) > Number(item.nowReturnNumber))).length > 0) {
              this.$message({
                message: returnNumberNameList + '退料数量不得大于可退数量',
                type: 'warning'
              })
              return
            }
          }
          if (this.formData.model == '0') { // 工艺要求模式
            let returnNumberNameList = []
            this.tableData.filter(item => {
              if (item.requisitionOrReturn == '1') {
                if (Number(item.nowReturnNumber) <= Number(item.returnNumber)) {
                  if (returnNumberNameList.length < 3) {
                    returnNumberNameList.push(item.materialName)
                  } else {
                    returnNumberNameList.push('等物料')
                  }
                  returnNumberNameList = this.materialNameArr(returnNumberNameList)
                }
              }
            })
            if (returnNumberNameList.includes('等物料')) {
              returnNumberNameList.splice(returnNumberNameList.indexOf('等物料'), 1)
              returnNumberNameList += '等物料'
            }

            if (this.tableData.filter(item => (Number(item.returnNumber) > Number(item.nowReturnNumber)) && (item.requisitionOrReturn == '1')).length > 0) {
              this.$message({
                message: returnNumberNameList + '退料数量不得大于可退数量',
                type: 'warning'
              })
              return
            }
          }

          this.formData.returnDate = this.formData.returnDate ? moment(this.formData.returnDate).format('YYYY-MM-DD') : ''
          this.formData.data = JSON.parse(JSON.stringify(this.tableData))
          this.formData.data.forEach(ele => {
            delete ele.id
            ele.canReturnNumber = ele.nowReturnNumber
          })
          addOrUpdate({ ...this.formData, status: num }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getList() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid) // 关闭弹框
    }
    //
  }
}
</script>

<style lang="less" scoped>
.title {
  padding-left: 20px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  .form_padding {
    padding: 0 !important;
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .el-table th.el-table__cell > .cell {
  position: unset;
}
.order_header{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  .info_button{
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
  }
}
</style>
